/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.network;


public class ManagedServerConnection extends ManagedConnection {

	ManagedServer managedServer;
	
	public ManagedServerConnection(ManagedServer managedServer, IEndpointCoordinator coordinator) {
		this.managedServer = managedServer;
		this.endpointCoordinator = coordinator;
	}

	@Override
	public void fireOnConnected() {
		synchronized(connectionListeners) {
			if(!connectionStatus) {
				connectionStatus = true;
				managedServer.fireOnConnected(this);
			}
		}
	}
	
	@Override
	public void assignConnectionHandler(ConnectionHandler handler) {
		synchronized(handlers) {
			super.assignConnectionHandler(handler);
			updateEndpointLocation();
		}
	}	


	@Override
	public void unassignConnectionHandler(ConnectionHandler handler) {
		synchronized(handlers) {
			super.unassignConnectionHandler(handler);
			updateEndpointLocation();
		}
	}
	
	protected void updateEndpointLocation() {
		if(!handlers.isEmpty()) {
			this.endpointLocation = new EndpointLocation(endpointCoordinator.getName());
			for(ConnectionHandler handler: handlers) {
				this.endpointLocation.getLocations().add(handler.getConnection().getEndpointURI());
			}
		}
		else
			this.endpointLocation = null;
	}	

	@Override
	public synchronized void stop() {
		managedServer.removeManagedConnection(this);
		connectionStatus = false;
		synchronized(handlers) {
			for(ConnectionHandler handler : handlers) {
				managedServer.removeHandler(handler);
				handler.getConnection().delConnectionListener(handler);				
				handler.getConnection().close();				
			}
			handlers.clear();
			updateEndpointLocation();
		}
	}
	
	public void finalize() {
		stop();
	}
}
